const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')

exports.regUser = (req, res) => {
    const userinfo = req.body
    // if (!userinfo.userName || !userinfo.passWord) {
    //     return res.send({ code: -1, msg: '用户名或密码不能为空！' })
    //     return res.cc('用户名或密码不能为空！')
    // }
    const sqlStr = 'select * from ev_users where userName=?'
    db.query(sqlStr, userinfo.userName, (err, results) => {
        if (err) {
           // return res.send({ code: -1, msg: err.msg })
            return res.cc(err)
        }
        if (results.length > 0) {
            // return res.send({ code: -1, msg: '账号已被占用，请注册其它账号' })
            return res.cc('账号已被占用，请注册其它账号')
        }
        userinfo.passWord = bcrypt.hashSync(userinfo.passWord, 10)
        console.log(userinfo.passWord)
        const sqlSet = 'insert into ev_users set?'
        db.query(sqlSet, { userName: userinfo.userName, passWord: userinfo.passWord }, (err, results) => {
            if (err) {
               // return res.send({ code: -1, msg: err.msg })
               return res.cc(err)
            }
            if (results.affectedRows !== 1) {
               // return res.send({ code: -1, msg: '账号注册失败，请稍后再试' })
               return res.cc('账号注册失败，请稍后再试')
            }
            // res.send({ code: 200, msg: '注册成功' })
            res.cc('注册成功',0)
        })
    })
   // res.send('register success')
}

exports.login = (req, res) => {
    const userinfo = req.body
    const sql = `select * from ev_users where userName=?`
    db.query(sql,userinfo.userName,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length) return rec.cc('登陆失败')
        const compareResults = bcrypt.compareSync(userinfo.passWord,results[0].passWord)
        if(!compareResults) return rec.cc('密码错误',1001)

        res.send(userinfo)
    })
    
}